<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class News extends My_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model("News_model","news");
    }

    /**
     *------------------------------------------------------------------------------------------------------------------
     * @title：首页新闻接口
     * @action：/news/index
     * @method：GET
     * @author:：KevinBai
     *------------------------------------------------------------------------------------------------------------------
     */
    public function index(){
        $this->isArrays = true;
        $params['per_page'] = $this->queryData['per_page'];
        $params['categoryid'] = $this->queryData['categoryid'];
        $params['readonly'] = $this->queryData['readonly'];
        $params['region'] = $this->queryData['region'];
        $validate = new Validate([
            'per_page' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $limit  = $this->config->item('limit');
        $params['reviewcnt'] = 1;
        $newsList = $this->news->getNewsList($params,$params['per_page'], $limit," newsID,title,transferfrom,content,addtime,cover,categoryid");
        foreach ($newsList as $key => $value) {
            $newsList[$key]['cover'] = $value['cover']?OSSHOST.$value['cover']:'';
            $newsList[$key]['content'] = cutstr(strip_tags($value['content']),30);
            $newsList[$key]['addtime'] = humanDate($value['addtime']);
            $newsList[$key]['reivewCnt'] = intval($this->news->getNewsReviewCnt($value['newsID']));
            $newsList[$key]['praiseCnt'] = $this->news->getPraiseCnt($value['newsID']);
            $newsList[$key]['praiseStatus'] = 0;
            if($this->userDetail['username']){
              $newsList[$key]['praiseStatus'] = $this->news->hasSetPraise($value['newsID'],$this->userDetail['username']);
            }

        }
        $this->createApi($newsList); exit();
    }


    public function activityList(){
        $this->isArrays = true;
        $params['per_page'] = $this->queryData['per_page']?$this->queryData['per_page']:1;
        $params['region'] = $this->queryData['region'];
        $validate = new Validate([
            'per_page' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $limit  = $this->config->item('limit');
        $newsList = $this->news->getActivityList($params,$params['per_page'], $limit," DISTINCT ques.questionID,n.newsID,n.title,n.transferfrom,n.content,n.addtime,n.cover,n.categoryid");
        $userInfo = $this->userDetail;
        $this->load->model('Examination_model', 'examination');
		
        foreach ($newsList as $key => $value) {
			
           // $newsList[$key]['statue'] = $this->examination->hasAnswered(['questionID'=>$value['questionID'],'AccountID'=>$userInfo['AccountID'],'newsID'=>$value['newsID']]);
            $newsList[$key]['cover'] = $value['cover']?OSSHOST.$value['cover']:'';
            $newsList[$key]['content'] = cutstr(strip_tags($value['content']),30);
            $newsList[$key]['addtime'] = humanDate($value['addtime']);
            $newsList[$key]['reivewCnt'] = intval($this->news->getNewsReviewCnt($value['newsID']));
            $newsList[$key]['praiseCnt'] = $this->news->getPraiseCnt($value['newsID']);
            $newsList[$key]['praiseStatus'] = 0;
			$newsList[$key]['status'] = 0;
            if($this->userDetail['username']){
				$newsList[$key]['praiseStatus'] = $this->news->hasSetPraise($value['newsID'],$this->userDetail['username']);
				$newsList[$key]['status'] = $this->answerStatus($value['newsID'],$userInfo['AccountID']);
			}
			//
			
			
        }
        $this->createApi($newsList); exit();
    }
	
	// 0: 未答 1：已答 -2：审核未通过 2：待审核
	public function answerStatus($newsID,$AccountID)
	{
		$this->load->model('Examination_model', 'examination');
		$status = 0;
		$fields = " ques.*,ans.isright,ans.ID,ans.AccountID ";
		$quesJoinAnsList = $this->examination->getQuesJoinAnsList($newsID,$AccountID,$fields);
		foreach($quesJoinAnsList as $key=>$qa)
		 {
			 if($qa['ID'] == "")
			 {
				 //没答完 未答
				 $status = 0;
				 break;
			 }else{
				 if($qa['questionType'] == 3 && $qa['isright'] == -1)
				 {
					 //图文审核未通过
					 $status = -2;
					 break;
				 }
				 if(in_array($qa['isright'],[1,-1]))
				 {
					  //已答
					 $status = 1;
				 }else{
					 //有图文&&待审核
					 $status = 2;
					 break;
				 }
			 }
		 }
		 return $status;
	}
    /**
     *------------------------------------------------------------------------------------------------------------------
     * @title：推荐新闻接口
     * @action：/news/recommend
     * @method：GET
     * @author:：KevinBai
     *------------------------------------------------------------------------------------------------------------------
     */
    public function recommendList(){
        $this->isArrays = true;
        $params['per_page'] = $this->queryData['per_page'];
        $params['region'] = $this->queryData['region'];
        $validate = new Validate([
            'per_page' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $limit  = $this->config->item('limit');
        //readonly 就是推荐
        $params['readonly'] = 1;
        $newsList = $this->news->getNewsList($params,$params['per_page'], $limit," newsID,title,transferfrom,content,addtime,cover,categoryid");
        foreach ($newsList as $key => $value) {
            $newsList[$key]['cover'] = $value['cover']?OSSHOST.$value['cover']:'';
            $newsList[$key]['content'] = cutstr(strip_tags($value['content']),30);
            $newsList[$key]['addtime'] = humanDate($value['addtime']);
            $newsList[$key]['reivewCnt'] = intval($this->news->getNewsReviewCnt($value['newsID']));
        }
        $this->createApi($newsList); exit();
    }

//新闻评论详情列表
    public function getReviewList(){
        $this->isArrays = true;
         $params['newsID']= $this->queryData['newsID']?$this->queryData['newsID']:8;
         $validate = new Validate([
            'newsID' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $reviewList = $this->news->getRiviewInfo($params['newsID']);
        foreach ($reviewList as $key => $value) {
            $reviewList[$key]['avatar'] = imgFormat($value['avatar']);
            $reviewList[$key]['createtime'] = humanDate($value['createtime']);
            $reviewList[$key]['praiseCnt'] = $this->news->getReviewPraiseCnt($value['reviewId']);
            $reviewList[$key]['praiseStatus'] = 0;
            if($this->userDetail['username']){
              $reviewList[$key]['praiseStatus'] = $this->news->hasSetReviewPraise($value['reviewId'],$this->userDetail['username']);
            }
        }
        $this->createApi($reviewList);
    }

/**
     *------------------------------------------------------------------------------------------------------------------
     * @title：首页新闻搜索接口
     * @action：/news/index
     * @method：GET
     * @author:：KevinBai
     *------------------------------------------------------------------------------------------------------------------
     */

      public function searchNews(){
        $this->isArrays = true;
        $limit  = $this->config->item('limit');
        $params['per_page'] = $this->queryData['per_page']?$this->queryData['per_page']:1;
        $params['keyword'] = $this->queryData['keyword'];
        $validate = new Validate([
            'per_page' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $newsList = $this->news->getNewsList(array('keyword'=>$params['keyword']),$params['per_page'], $limit,"newsID,title,transferfrom,content,addtime,cover");
        foreach ($newsList as $key => $value) {
            $newsList[$key]['content'] = cutstr(strip_tags($value['content']),30);
            $newsList[$key]['cover'] = OSSHOST.$value['cover'];
            $newsList[$key]['addtime'] = humanDate($value['addtime']);
            $newsList[$key]['reivewCnt'] = intval($this->news->getNewsReviewCnt($value['newsID']));
        }
        $this->createApi($newsList); exit();
    }


    /**
     *------------------------------------------------------------------------------------------------------------------
     * @title：首页新闻获取更多
     * @action：/news/moreNewsList
     * @method：GET
     * @author:：KevinBai
     *------------------------------------------------------------------------------------------------------------------
     */


    /**
     *------------------------------------------------------------------------------------------------------------------
     * @title：发布动态
     * @action：/dynamic/publishDynamic
     * @method：POST
     * @author:：柏凯
     *------------------------------------------------------------------------------------------------------------------
     */
    public function publishReview(){
        $params['content'] = $this->queryData['content']; //动态内容
        $params['newsID'] = $this->queryData['newsID']; //动态内容
        $validate = new Validate([
            'content' => 'require|string',
            'newsID' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $userInfo = $this->userDetail;
        $data = array(
            'fromUsername'=>$userInfo['username'],
            'newsID'=>$params['newsID'],
            'content'=>$params['content'],
            'createtime'=>time()
            );
        $res = $this->news->publishNewsReview($data,$picList);        
        $this->createApi();
        exit();
    }


    /**
     *------------------------------------------------------------------------------------------------------------------
     * @title：新闻详情
     * @action：/news/newsDetail
     * @method：POST
     * @author:：柏凯
     * @date：2015-11-13
     *------------------------------------------------------------------------------------------------------------------
     */
    public function newsDetail(){
        $params['newsID'] = $this->queryData['newsID'];
        $validate = new Validate([
            'newsID' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $data = array();
        $newsDetail = $this->news->getNewsDetail($params['newsID'],"newsID,title,transferfrom,content,addtime,cover,isruanwen");
        if($newsDetail){
            $newsDetail['hasCollected'] = 0;
            $newsDetail['addtime'] = date("Y-m",$newsDetail['addtime']); 
            $newsDetail['content'] = ($newsDetail['content']);
            // $newsDetail['content'] = replaceTextareaImageUrl($newsDetail['content']);
            $reviewList = $this->news->getReviewList($params['newsID']);
            foreach ($reviewList as $key => $value) {
                $reviewList[$key]['createtime'] = humanDate($value['createtime']);
		            $reviewList[$key]['avatar'] =imgFormat($value['avatar']);
                    $reviewList[$key]['praiseCnt'] = $this->news->getReviewPraiseCnt($value['reviewId']);
                    $reviewList[$key]['praiseStatus'] = 0;
                    if($this->userDetail['username']){
                      $reviewList[$key]['praiseStatus'] = $this->news->hasSetReviewPraise($value['reviewId'],$this->userDetail['username']);
                    }
            }
            $newsDetail['reviewCnt'] = count($reviewList) ? count($reviewList) : 0 ;
      	    $shareInfo = array(
                 'title'=>$newsDetail['title'],
                 'content'=>cutstr(strip_tags($newsDetail['content']),50,""),
                 'image'=>$newsDetail['cover']? OSSHOST.$newsDetail['cover']:'',
                 'url'=>BASEURL.'news/detail?id='.$params['newsID']
              );
      		$newsDetail['content_url'] ='http://'.$_SERVER['HTTP_HOST'].'/news/getcontent?id='.$params['newsID'];
          $newsDetail['shareInfo']=$shareInfo;
            //判断该新闻信息是否被收藏过
            if($this->userDetail){
                $username = $this->userDetail['username'];
                $collectInfo = $this->news->checkSetCollected(array('fromUsername'=>$username,'newsID'=>$params['newsID']));
                if($collectInfo){
                    $newsDetail['hasCollected'] = 1;    
                }
                
            }
            //阅读计数
                $this->news->newsUpdate($params['newsID']);

            $data = array(
                'newsDetail'=>$newsDetail,
                'reviewList'=>$reviewList
                );
            $this->createApi($data);
        }else{
            $this->errorCode = 50008;
            $this->createApi();exit;
        }
    }
 public function detail(){
        $params['id'] =  $this->input->get("id");
        $validate = new Validate([
            'id' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $data = array();
        $newsDetail = $this->news->getNewsDetail($params['id'],"newsID,title,transferfrom,content,addtime,cover");
        if($newsDetail){
            $newsDetail['addtime'] = date("Y-m",$newsDetail['addtime']); 
            $newsDetail['content'] = ($newsDetail['content']);
            // $newsDetail['content'] = replaceTextareaImageUrl($newsDetail['content']);
            $reviewList = $this->news->getReviewList($params['id']);
            
            $newsDetail['reviewCnt'] = count($reviewList) ? count($reviewList) : 0 ;
            
          $newsDetail['content_url'] ='http://'.$_SERVER['HTTP_HOST'].'/news/getcontent?id='.$params['id'];
            //判断该新闻信息是否被收藏过
            if($this->userDetail){
                $username = $this->userDetail['username'];
                $collectInfo = $this->news->checkSetCollected(array('fromUsername'=>$username,'newsID'=>$params['id']));
                if($collectInfo){
                    $newsDetail['hasCollected'] = 1;    
                }
                
            }
            //阅读计数
                $this->news->newsUpdate($params['id']);

            $data = array(
                'newsDetail'=>$newsDetail,
                'reviewList'=>$reviewList
                );
        }
       $this->load->view("/news/detail1",$data); 
    }

public function getContent(){
        $newsID = $this->input->get("id");
        if(empty($newsID)){
            echo "参数不能为空";
            exit;
        }
        $data = array();
        $newsDetail = $this->news->getNewsDetail($newsID,"newsID,title,transferfrom,content,addtime,videourl");
        if($newsDetail){
            $newsDetail['addtime'] = date("Y-m",$newsDetail['addtime']);
            $newsDetail['content'] = replaceTextareaImageUrl($newsDetail['content']);
            $reviewList = $this->news->getReviewList($newsID);
            foreach ($reviewList as $key => $value) {
                $reviewList[$key]['createtime'] = humanDate($value['createtime']);
            }
            $data = array(
                'newsDetail'=>$newsDetail,
                );
        }
       $this->load->view("/News/detail1",$data);
    }

    /**
     *------------------------------------------------------------------------------------------------------------------
     * @title：对新闻添加收藏，取消收藏
     * @action：/dynamic/doCollect
     * @param  $status 1:取消收藏，2：添加收藏
     * @method：POST
     * @author:：柏凯
     * @date：2015-11-14
     *------------------------------------------------------------------------------------------------------------------
     */
    public function setCollect(){
        file_put_contents("mylog.txt", json_encode($this->json_content)."\r\n",FILE_APPEND);
        $params['newsID'] = $this->queryData['newsID'];
        $params['type'] = $this->queryData['type']?$this->queryData['type']:0;
        $validate = new Validate([
            'newsID' => 'require|number',
            'type' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $fromUsername = $this->userDetail['username'];
        $data = array(
                'newsID'=>$params['newsID'],
                'fromUsername'=>$fromUsername,
                'createtime'=>time(),
                );
        $res = $this->news->setCollect($data,$params['type']);
        if($res === 70001){
            $this->errorCode = 70001;
        }
        elseif(!$res){
            $this->errorCode = 50006;
        }
        $this->createApi();
    }



    public function setReviewPraise(){
        $params['reviewid'] = $this->queryData['reviewid'];
        $params['type'] = $this->queryData['type']?$this->queryData['type']:0;
        $validate = new Validate([
            'reviewid' => 'require|number',
            'type' => 'require|number',
        ]);
        if (!$validate->check($params)) 
        {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $data = array(
                'reviewid'=>$params['reviewid'],
                'fromUsername'=>$this->userDetail['username'],
                'createtime'=>time(),
                );
        $res = $this->news->setReviewPraise($data,$params['type']);
        if($res === 70003){
            $this->errorCode = 70003;
        }
        elseif(!$res){
            $this->errorCode = 50006;
        }
        $this->createApi();
    }


    public function setPraise(){
        $params['newsID'] = $this->queryData['newsID'];
        $params['type'] = $this->queryData['type']?$this->queryData['type']:0;
        $validate = new Validate([
            'newsID' => 'require|number',
            'type' => 'require|number',
        ]);
        if (!$validate->check($params)) 
        {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $data = array(
                'newsID'=>$params['newsID'],
                'fromUsername'=>$this->userDetail['username'],
                'createtime'=>time(),
                );
        $res = $this->news->setPraise($data,$params['type']);
        if($res === 70003){
            $this->errorCode = 70003;
        }
        elseif(!$res){
            $this->errorCode = 50006;
        }
        $this->createApi();
    }

      //添加会员积分
    public function setPoints(){
        $params['newsID'] = $this->queryData['newsID'];
        $params['type'] = $this->queryData['type'];
        $validate = new Validate([
            'newsID' => 'require|number',
            'type' => 'require|string',
        ]);
        if (!$validate->check($params)) 
        {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $type_arr = ['normal'=>3,'ruanwen'=>4,'share'=>5];

        $userInfo = $this->userDetail;
        $points = $this->setPoint($type_arr[$type]);
        $data = array(
            'AccountID'=>$userInfo['AccountID'],
            'createtime'=>date('Y-m-d',time()),
            'points'=>$points?$points:0,
            'type'=>1
            );
        $res = $this->user->addPoints($userInfo['AccountID'], $data);

        $this->createApi(['addPointCnt'=>$points]);
    }
}

/* End of file region.php */
/* Location: ./application/controllers/region.php */
